package com.dfiov.cloud.msmtools.service.bussiness.impl;
import com.dfiov.cloud.msmtools.config.Constants;
import com.dfiov.cloud.msmtools.config.RedisConfigProperties;
import com.dfiov.cloud.msmtools.service.bussiness.RedisViewService;
import com.dfiov.cloud.msmtools.utils.ResponseUtils;
import com.dfiov.cloud.msmtools.vo.RedisCon;
import com.pateo.qingcloud.framework.common.base.BaseRestResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;



@Service
public class RedisViewServiceImpl implements RedisViewService {

    @Autowired
    private RedisConfigProperties redisConfigProperties;

    @Override
    public BaseRestResponse viewValue(String key, String dataBase, String redisChoose) {
        StringBuffer target = new StringBuffer("redis").append(redisChoose);
        RedisCon redisCon = redisConfigProperties.getRedisMap().get(target.toString());
        Jedis jedis = new Jedis(redisCon.getHost(), Integer.parseInt(redisCon.getPort()));
        try{
            jedis.auth(redisCon.getPassword());
            if(!jedis.exists(key)){
                return ResponseUtils.success(Constants.NOT_FOUND_KEY);
            }
            String type = jedis.type(key).toLowerCase();
            if(type.equals(Constants.KEY_STRING)){
                return ResponseUtils.success(jedis.get(key));
            }else if(type.equals(Constants.KEY_LIST)){
                return ResponseUtils.success(jedis.lrange(key,0,-1));
            }else if(type.equals(Constants.KEY_HASH)){
                return ResponseUtils.success(jedis.hgetAll(key));
            }else if(type.equals(Constants.KEY_SET)){
                return ResponseUtils.success(jedis.smembers(key));
            }else if(type.equals(Constants.KEY_ZSET)){
                return ResponseUtils.success(jedis.zrangeWithScores(key,0,-1));
            }
        }finally {
            jedis.close();
        }
        return ResponseUtils.success(Constants.NOT_FOUND_KEY);
    }


}
